import zijieConfig from "../zijieConfig";


export default class InterstitialManager {

    public static _s_instance: InterstitialManager | null = null;
    public static getInstance(): InterstitialManager {
        if (!this._s_instance) {
            this._s_instance = new InterstitialManager();
            this._s_instance.initInterstial();
        }

        return this._s_instance;
    }

    tt: any = null;
    private _interstitialAd: any = null;
    private _isLoadInterstitialAd: boolean = false;

    private initInterstial() {
        this.tt = window["tt"] || undefined;

        if (this.tt == null)
            return;
        if (this.tt == undefined)
            return;

        this._interstitialAd = this.tt.createInterstitialAd({
            adUnitId: zijieConfig._ad_interstitial,
        });

        this.loadInterstitialAd();

        this._interstitialAd.onLoad(() => {
            console.log('插屏广告加载成功')
        })
        this._interstitialAd.onError(err => {
            console.log(err)
        })
        this._interstitialAd.onClose(res => {
            console.log('插屏 广告关闭')
            this._isLoadInterstitialAd = false;
            this.loadInterstitialAd();
        })

    }

    /**
     * 加载插屏广告
     * @returns 
     */
    private loadInterstitialAd() {
        if (this.tt == undefined)
            return;

        this._isLoadInterstitialAd = false;
        this._interstitialAd
            .load()
            .then(() => {
                console.log("interstitial广告加载完成");
                this._isLoadInterstitialAd = true;
            })
            .catch((err) => {
                console.log("interstitial广告出现问题", err);
            });
    }

    /**
     * 展示插屏广告
     * @returns 
     */
    public showInterstitialAd() {
        if (this.tt == undefined)
            return;

        if (this._isLoadInterstitialAd)
            this._interstitialAd.show();
        else
            this.loadInterstitialAd();
    }
}
